import React, {Component} from 'react';

export default class App extends Component {
    state = {
        count: 0
    }
    // 使用箭头函数保证 this 是组件对象
    increment = () => {
        // debugger
        // 获取当前值
        let {count} = this.state
        // 获取selection选中的值
        const {value} = this.select;
        count += value * 1;

        // 更新转态
        this.setState({count})

    }
    decrement = () => {
        // 获取当前值
        let {count} = this.state

        // 获取selection选中的值
        const {value} = this.select;
        count -= value * 1;

        // 更新转态
        this.setState({count})

    }
    incrementIfOdd = () => {
        // 获取当前值
        let {count} = this.state

        // 获取selection选中的值
        const {value} = this.select;

        // 判断满足状态才更新
        if (count % 2 === 1) {
            // 更新状态
            count += value * 1;

            // 更新转态
            this.setState({count})
        }


    }
    incrementAsync = () => {
        // 获取当前值
        let {count} = this.state

        // 获取selection选中的值
        const {value} = this.select;
        count += value * 1;

        // 启动延时定时器
        setTimeout(() => {
            // 更新转态
            this.setState({count})
        }, 1000)

    }

    render() {
        const {count} = this.state
        return (
            <div>
                <p>click {count} times</p>
                <div>
                    <select ref={(input) => this.select = input}>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>&nbsp;
                    <button onClick={this.increment}>+</button>
                    &nbsp;
                    <button onClick={this.decrement}>-</button>
                    &nbsp;
                    <button onClick={this.incrementIfOdd}>increment if odd</button>
                    &nbsp;
                    <button onClick={this.incrementAsync}>increment async</button>
                </div>
            </div>
        );
    }
};